package com.kedou.sdk.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import com.alipay.sdk.app.AuthTask;
import com.bytedance.applog.AppLog;
import com.bytedance.applog.game.GameReportHelper;
import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.assist.CallbackObservable;
import com.kedou.sdk.assist.Constant;
import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.core.HttpEngineConduits;
import com.kedou.sdk.download.VersionUpdateDownloader;
import com.kedou.sdk.handler.SimpleAsyncResponseHandler;
import com.kedou.sdk.params.AccountInfosResponseParams;
import com.kedou.sdk.params.AccountInfosTokenResponseParams;
import com.kedou.sdk.params.AlipayAuthResponseParams;
import com.kedou.sdk.params.AuthLoginResponseParams;
import com.kedou.sdk.params.BindPhoneResponseParams;
import com.kedou.sdk.params.CreatSmallAccountResponseParams;
import com.kedou.sdk.params.GetUuidResponseParams;
import com.kedou.sdk.params.LoginResponseParams;
import com.kedou.sdk.params.ModifyPasswordResponseParams;
import com.kedou.sdk.params.QuickRegisterResponseParams;
import com.kedou.sdk.params.RealNameResponseParams;
import com.kedou.sdk.params.RegisterResponseParams;
import com.kedou.sdk.params.ResponseParams;
import com.kedou.sdk.params.bean.AccountInfo;
import com.kedou.sdk.params.bean.LoginInfo;
import com.kedou.sdk.params.bean.NoticePopup;
import com.kedou.sdk.params.bean.Popup;
import com.kedou.sdk.params.bean.SimpleUserInfo;
import com.kedou.sdk.params.bean.State;
import com.kedou.sdk.params.bean.UserInfo;
import com.kedou.sdk.params.bean.VersionInfo;
import com.kedou.sdk.ui.assist.LoginTypeSwitchWatcher;
import com.kedou.sdk.ui.assist.OnThirdLoginListener;
import com.kedou.sdk.ui.assist.ThirdLoginUtil;
import com.kedou.sdk.ui.content.TimeTaskService;
import com.kedou.sdk.ui.fragment.AccountListChangeDialogFragment;
import com.kedou.sdk.ui.fragment.AccountListDialogFragment;
import com.kedou.sdk.ui.fragment.AccountListTokenDialogFragment;
import com.kedou.sdk.ui.fragment.AutoLoginDialogFragment;
import com.kedou.sdk.ui.fragment.BaseDialogFragment;
import com.kedou.sdk.ui.fragment.CertifiesChooseDialogFragment;
import com.kedou.sdk.ui.fragment.ChangePwdDialogFragment;
import com.kedou.sdk.ui.fragment.ChangePwdFinalDialogFragment;
import com.kedou.sdk.ui.fragment.CreateXiaohaoFragment;
import com.kedou.sdk.ui.fragment.DownloadDialogFragment;
import com.kedou.sdk.ui.fragment.GameNoticeFragment;
import com.kedou.sdk.ui.fragment.LoginBindDialogFragment;
import com.kedou.sdk.ui.fragment.LoginDialogFragment;
import com.kedou.sdk.ui.fragment.LoginDialogFragment2;
import com.kedou.sdk.ui.fragment.NoticeTipDialogFragment;
import com.kedou.sdk.ui.fragment.RealNameDialogFragment;
import com.kedou.sdk.ui.fragment.RegisterDialogFragment;
import com.kedou.sdk.ui.fragment.RegisterPhoneDialogFragment;
import com.kedou.sdk.ui.view.ConfirmDialog;
import com.kedou.sdk.ui.view.DialogFactory;
import com.kedou.sdk.utils.CommonUtils;
import com.kedou.sdk.utils.WL;
import com.kedou.sdk.utils.XmlUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/7 0007.
 */
public class UserLoginActivity extends PhoneVerifyActivity implements LoginDialogFragment.OnUserActionListener,
        ChangePwdDialogFragment.OnChangeUserPasswordListener, RegisterDialogFragment.OnQuickRegisterListener,
        LoginBindDialogFragment.OnUserLoginActionListener, AccountListDialogFragment.OnUserLoginActionListener,
         AutoLoginDialogFragment.OnAutoLoginActionListener,CertifiesChooseDialogFragment.OnAlipayAuthListener
        ,AccountListTokenDialogFragment.OnCreateXiaohaoActionListener,AccountListTokenDialogFragment.OnUserLoginActionListener,
CreateXiaohaoFragment.OnUserLoginActionListener, RealNameDialogFragment.OnUserLoginActionListener,AccountListChangeDialogFragment.OnUserLoginActionListener,
        ChangePwdFinalDialogFragment.OnChangeUserPasswordListener,
RegisterPhoneDialogFragment.OnQuickRegisterListener{

    private static final String TAG = UserLoginActivity.class.getSimpleName();

    private static final String FLAG_LOGIN_FRAGMENT = "login";
    private static final String FLAG_Bind_PHONE = "band_phone";
    private static final String FLAG_LOGIN_FRAGMENT_more = "login_more";
    private static final String FLAG_LOGIN_FRAGMENT_createxiaohao = "createxiaohao";
    private static final String FLAG_LOGIN_FRAGMENT_REGIST_PHONE = "register_phone";
    private static final String FLAG_AUTO_LOGIN_FRAGMENT = "auto_login";
    private static final String FLAG_GUEST_REGISTER_FRAGMENT = "guest";
    private static final String FLAG_PASSWORD_FRAGMENT = "password";
    private static final String FLAG_REGISTER_FRAGMENT = "register";
    private static final String FLAG_REALNAME_FRAGMENT = "realname";
    private static final String FLAG_NOTICE_FRAGMENT = "notice";
    private static final String FLAG_ACCOUNT_FRAGMENT = "account";
    private static final String FLAG_ACCOUNT_LIST_FRAGMENT = "account_list";
    private static final String FLAG_CERTIFIES_FRAGMENT = "certifies";
    private static final String FLAG_CERTIFIES_CHOOSE_FRAGMENT = "certifies_choose";
    private static final String FLAG_VERSION_UPDATE_FRAGMENT = "version_update";
    private static final String FLAG_GAME_NOTICE_FRAGMENT = "game_notice";


    private int mSubmitLoginInfoTaskId;
    private int thirdAuthTaskId;
    private int mSumbitUserPasswordInfoTaskId;
    private int mSumbitRegisterInfoTaskId;
    private int mSumbitVerifyInfoTaskId;
    private int mAlipayAuthTaskId,mAlipayRealnameTaskId;
    private LoginBindDialogFragment  mBindPhoneFragment;
    private BaseDialogFragment mLoginFragment;
    private BaseDialogFragment mMoreLoginFragment;
    private CreateXiaohaoFragment createXiaohaoFragment;
    private AccountListChangeDialogFragment accountListChangeDialogFragment;
//    private GuestRegisterDialogFragment mGuestRegisterFragment;
    private AutoLoginDialogFragment mAutoLoginDialogFragment;
    private DownloadDialogFragment mVersionUpdateDialogFragment;
    private ChangePwdDialogFragment mChangePasswordFragment;
    private ChangePwdFinalDialogFragment mChangePasswordFinalFragment;
    private RegisterDialogFragment mQuickRegisterFragment;
    private RegisterPhoneDialogFragment mRegisterPhoneFragment;
    private RealNameDialogFragment mRealNameVerifyFragment;
    private NoticeTipDialogFragment mNoticeTipFragment;
//    private AccountDialogFragment mAccountFragment;
    private AccountListDialogFragment mAccountListDialogFragment;
    private AccountListTokenDialogFragment mAccountListTokenDialogFragment;
//    private CertifiesTipDialogFragment mCertifiesTipFragment;
    private GameNoticeFragment mGameNoticeFragment;
    private CertifiesChooseDialogFragment mCertifiesChooseFragment;

    private int mCurrentLoginType = XmlUtils.isPutInChannel()&&"3.1.12".equals(XmlUtils.getSdkVersionName())?LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_CELLPHONE:LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT;

    public final void setCurrentLoginType(int loginType) {
        Log.e("loginType",loginType+"");
        this.mCurrentLoginType = loginType;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkAppSelfPermission(Manifest.permission.READ_PHONE_STATE);

        //是否为绑定手机
        if (isBindPhone()) {
           doNextToBindPhone(null,savedInstanceState);

        }

//        //是否为游客登录定时提示实名认证
//        else if (isOnlyRealNameVerify()) {
//            PopupConfig popupConfig = getIntent().getParcelableExtra(Constant.LocalIntentExtra.INTENT_KEY_LOGIN_BINDING_DATA);
//            Bundle bundle = new Bundle();
//            bundle.putParcelable("PopupConfig", popupConfig);
//
//            doNextToCertifiesTip(null, bundle);
//        }

        //检查是否有新版本更新升级
        else  if (CommonUtils.isUpdateVersion()) {
            if (CommonUtils.isForceUpdateVersion() || CommonUtils.existsDownloadedVersion()) {
                doNextToVersionUpdate(null);
            } else {
                HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
                VersionInfo newVersionInfo = conduits.readVersionInfo();

                //启动版本静默下载
                VersionUpdateDownloader versionUpdateManager = VersionUpdateDownloader.getImpl();
                File storageFile = versionUpdateManager.randomMakeDownloadStorageFile(String.valueOf(newVersionInfo.getVersionCode()));
                versionUpdateManager.startVersionDownloadTask(newVersionInfo.getUrl(), storageFile, false);

                //执行登录
                executeLoginProcess(null);
            }
        }

        //执行登录
        else {
            executeLoginProcess(null);
        }

    }


//    private MyBroadcastReciver myReciver;

    private void executeLoginProcess(DialogFragment fragment) {
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        List<AccountInfo> accountInfos = wanSDKDataDao.readAllUserAccountInfo();
        Log.e(TAG ,wanSDKDataDao.readAutoLogin()+"..."+(accountInfos == null || accountInfos.isEmpty()));
            if (!wanSDKDataDao.readAutoLogin()||accountInfos == null || accountInfos.isEmpty()) {
                doNextToLogin(fragment, wanSDKDataDao.readLastLoginType());
            }else {
                doNextToAutoLogin(fragment);
            }


    }







    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if(XmlUtils.showThirdLogin()&&myReciver!=null){
//            unregisterReceiver(myReciver);
//        }
        HttpEngineApi.getInstance().cancel(mSubmitLoginInfoTaskId);
        HttpEngineApi.getInstance().cancel(mSumbitUserPasswordInfoTaskId);
        HttpEngineApi.getInstance().cancel(mSumbitRegisterInfoTaskId);
        HttpEngineApi.getInstance().cancel(mSumbitVerifyInfoTaskId);
    }

    private boolean isOnlyRealNameVerify() {
        Intent intent = getIntent();
        if (intent != null) {
            String loginInitPosition = intent.getStringExtra(Constant.LocalIntentExtra.INTENT_KEY_LOGIN_INIT_POSITION);
            return TextUtils.equals(Constant.LocalIntentExtra.INTENT_VALUE_LOGIN_INIT_BINDING, loginInitPosition);
        }
        return false;
    }

    private boolean isBindPhone() {
        Intent intent = getIntent();
        if (intent != null) {
            return intent.hasExtra(Constant.LocalIntentExtra.INTENT_KEY_LOGIN_BINDING_DATA);
        }
        return false;
    }

    private void switchDialogFragment(DialogFragment from, DialogFragment to, String tag) {
        if (from != null && !isSaveInstanceState()) {
            from.dismissAllowingStateLoss();
        }

        if (to != null && !isSaveInstanceState()) {
            to.show(getSupportFragmentManager(), tag);
        }

    }

    @Override
    public void doSubmitLoginAccountInfo(SimpleUserInfo user, String verify) {
           SimpleAsyncResponseHandler handler = requestCallbackHandler(AuthLoginResponseParams.class);
            mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().loginByVerify(user.getUsername(), verify, handler);
    }

    @Override
    public void doChangeSelectAccount(SimpleUserInfo userInfo) {
        Bundle bundle = accountListChangeDialogFragment.getArguments();
        bundle.putParcelable("user",userInfo);
        doNextToChangePasswordFinal(accountListChangeDialogFragment,bundle);
    }

    @Override
    public void doSubmitAuthLoginXiaohaoInfo(SimpleUserInfo userInfo) {
        Log.e("login","doSubmitAuthLoginXiaohaoInfo");
        SimpleAsyncResponseHandler handler = requestCallbackHandler(LoginResponseParams.class);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().xiaohaologin(userInfo.getId(), handler);
    }
    public void doSubmitAuthLoginXiaohaoInfo(String userid) {
        Log.e("login","doSubmitAuthLoginXiaohaoInfo");
        SimpleAsyncResponseHandler handler = requestCallbackHandler(LoginResponseParams.class);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().xiaohaologin(userid, handler);
    }



    @Override
    public void doSubmitLoginInfo(String username, String password) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AuthLoginResponseParams.class, username, password, "false");
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().login(username, password, handler);

    }

    @Override
    public void doAutoLoginInfo(String username, String password) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AccountInfosTokenResponseParams.class);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().getAccountInfosByToken(handler);
//        SimpleAsyncResponseHandler handler = requestCallbackHandler(LoginResponseParams.class, username, password, "true");
//        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().login(username, password, true, handler);
    }

    @Override
    public void doSubmitCellPhoneNumber(String cellphone, String verify) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AccountInfosResponseParams.class, cellphone, verify);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().getAccountInfosByPhone(cellphone, verify, handler);
    }

    @Override
    public void doCreateSmallAccount(String username) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(CreatSmallAccountResponseParams.class);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().createSmallAccount(username, handler);
    }

    @Override
    public void doNextToOneKeyLogin() {

            SimpleAsyncResponseHandler handler = requestCallbackHandler(QuickRegisterResponseParams.class);
            mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().quickRegister(handler);
    }

    @Override
    public void doNextToLoginMore() {

            mMoreLoginFragment = LoginDialogFragment.newInstance(mCurrentLoginType);
            switchDialogFragment(mLoginFragment, mMoreLoginFragment, FLAG_LOGIN_FRAGMENT_more);

    }

    private void doNextToLoginMore(DialogFragment fragment, int currentLoginType) {
        mMoreLoginFragment = LoginDialogFragment.newInstance(currentLoginType);
        switchDialogFragment(fragment, mMoreLoginFragment, FLAG_LOGIN_FRAGMENT_more);
//        this.mCurrentLoginType = currentLoginType;
//        Log.e("loginType","doNextToLogin."+currentLoginType);
//        mLoginFragment = LoginDialogFragment2.newInstance();
//        switchDialogFragment(fragment, mLoginFragment, FLAG_LOGIN_FRAGMENT);
    }

    @Override
    public void doNextToAppLogin() {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(GetUuidResponseParams.class);
        thirdAuthTaskId = HttpEngineApi.getInstance().getUuid(handler);
    }

    @Override
    public void doCreateXiaohao(BaseDialogFragment fragment) {
        createXiaohaoFragment =CreateXiaohaoFragment.newInstance(fragment.getArguments());
        switchDialogFragment(fragment, createXiaohaoFragment, FLAG_LOGIN_FRAGMENT_createxiaohao);
    }

    @Override
    public void doNextToQuickRegister() {
        mQuickRegisterFragment = RegisterDialogFragment.newInstance();
        switchDialogFragment(mMoreLoginFragment, mQuickRegisterFragment, FLAG_REGISTER_FRAGMENT);

    }

    @Override
    public void goPhoneRegister(BaseDialogFragment fragment) {
        mRegisterPhoneFragment = RegisterPhoneDialogFragment.newInstance();
        setOnPhoneVerifyCodeListener(mRegisterPhoneFragment);
        switchDialogFragment(fragment, mRegisterPhoneFragment, FLAG_LOGIN_FRAGMENT_REGIST_PHONE);
    }

    @Override
    public void doNextToChangePassword(String username) {
        Bundle bundle = new Bundle();
        bundle.putString("username", "");

        mChangePasswordFragment = ChangePwdDialogFragment.newInstance(bundle);
        setOnPhoneVerifyCodeListener(mChangePasswordFragment);
        switchDialogFragment(mMoreLoginFragment, mChangePasswordFragment, FLAG_PASSWORD_FRAGMENT);
    }

    @Override
    public void dofinalPassword(String username) {
        Bundle bundle = mChangePasswordFinalFragment.getArguments();
        SimpleAsyncResponseHandler handler = requestCallbackHandler(ModifyPasswordResponseParams.class, username);
        mSumbitUserPasswordInfoTaskId = HttpEngineApi.getInstance().modifyPasswordFinal(((SimpleUserInfo)bundle.getParcelable("user")).getUsername(), username, bundle.getString("code"), handler);

    }

    private void doNextToChangePassword(DialogFragment fragment, Bundle bundle) {
        mChangePasswordFragment = ChangePwdDialogFragment.newInstance(bundle);
        setOnPhoneVerifyCodeListener(mChangePasswordFragment);
        switchDialogFragment(fragment, mChangePasswordFragment, FLAG_PASSWORD_FRAGMENT);

    }
    private void doNextToChangePasswordFinal(DialogFragment fragment, Bundle bundle) {
        mChangePasswordFinalFragment = ChangePwdFinalDialogFragment.newInstance(bundle);
        switchDialogFragment(fragment, mChangePasswordFinalFragment, FLAG_PASSWORD_FRAGMENT);

    }

    private void doNextToRealNameVerify(DialogFragment fragment, Bundle bundle) {
        mRealNameVerifyFragment = RealNameDialogFragment.newInstance(bundle);
        switchDialogFragment(fragment, mRealNameVerifyFragment, FLAG_REALNAME_FRAGMENT);
    }


//    private void doNextToRealNameChoose(DialogFragment fragment, Bundle bundle) {
//        mCertifiesChooseFragment = CertifiesChooseDialogFragment.newInstance(bundle);
//        switchDialogFragment(fragment, mCertifiesChooseFragment, FLAG_CERTIFIES_CHOOSE_FRAGMENT);
//    }

//    private void doNextToOneKeyLogin(Bundle bundle) {
//                    mAccountFragment = AccountDialogFragment.newInstance(bundle);
//            switchDialogFragment(mLoginFragment, mAccountFragment, FLAG_ACCOUNT_FRAGMENT);
////        if(XmlUtils.showThirdLogin()){
////            SimpleAsyncResponseHandler handler = requestCallbackHandler(GetUuidResponseParams.class);
////            thirdAuthTaskId = HttpEngineApi.getInstance().getUuid(handler);
////        }else {
////            mAccountFragment = AccountDialogFragment.newInstance(bundle);
////            switchDialogFragment(mLoginFragment, mAccountFragment, FLAG_ACCOUNT_FRAGMENT);
////        }
////        ThirdLoginUtil.getInstance().startLogin(UserLoginActivity.this, new OnThirdLoginListener() {
////            @Override
////            public void doLoginFinish(int status, String code) {
////                if(status==1){
////                    SimpleAsyncResponseHandler handler = requestCallbackHandler(LoginResponseParams.class);
////                    mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().thirdlogin(code, handler);
////                }
////            }
////        });
//    }

    private void doNextToNoticeTip(DialogFragment fragment, Bundle bundle) {
        mNoticeTipFragment = NoticeTipDialogFragment.newInstance(bundle);
        switchDialogFragment(fragment, mNoticeTipFragment, FLAG_NOTICE_FRAGMENT);
    }
    private void doNextToBindPhone(DialogFragment fragment, Bundle bundle) {
        mBindPhoneFragment = LoginBindDialogFragment.newInstance(bundle);
//        mNoticeTipFragment = NoticeTipDialogFragment.newInstance(bundle);
        switchDialogFragment(fragment, mBindPhoneFragment, FLAG_NOTICE_FRAGMENT);
    }

    private void doNextToAccountList(DialogFragment fragment, Bundle bundle) {

            mAccountListDialogFragment = AccountListDialogFragment.newInstance(bundle);
            switchDialogFragment(fragment, mAccountListDialogFragment, FLAG_ACCOUNT_LIST_FRAGMENT);

    }
    private void doNextToAccountChangeList(DialogFragment fragment, Bundle bundle) {
        accountListChangeDialogFragment = AccountListChangeDialogFragment.newInstance(bundle);
        switchDialogFragment(fragment, accountListChangeDialogFragment, FLAG_ACCOUNT_LIST_FRAGMENT);

    }

    private void doNextToXiaohaoList(DialogFragment fragment, Bundle bundle) {

            mAccountListTokenDialogFragment = AccountListTokenDialogFragment.newInstance(bundle);
            switchDialogFragment(fragment, mAccountListTokenDialogFragment, FLAG_ACCOUNT_LIST_FRAGMENT);

    }

//    private void doNextToCertifiesTip(DialogFragment fragment, Bundle bundle) {
//        mCertifiesTipFragment = CertifiesTipDialogFragment.newInstance(bundle);
//        switchDialogFragment(fragment, mCertifiesTipFragment, FLAG_CERTIFIES_FRAGMENT);
//    }

    private void doNextToLogin(DialogFragment fragment, int currentLoginType) {
        this.mCurrentLoginType = currentLoginType;
        Log.e("loginType","doNextToLogin."+currentLoginType);
        if(ThirdLoginUtil.getInstance().isAppInstalled(getApplicationContext())){
            mLoginFragment = LoginDialogFragment2.newInstance();
            switchDialogFragment(fragment, mLoginFragment, FLAG_LOGIN_FRAGMENT);
        }else{
//            mLoginFragment = LoginDialogFragment2.newInstance();
//            switchDialogFragment(fragment, mLoginFragment, FLAG_LOGIN_FRAGMENT);
            mMoreLoginFragment = LoginDialogFragment.newInstance(currentLoginType);
            switchDialogFragment(fragment, mMoreLoginFragment, FLAG_LOGIN_FRAGMENT_more);
        }



    }


    private void doNextToGameNotice(DialogFragment fragment,Bundle bundle){
        mGameNoticeFragment = GameNoticeFragment.newInstance(bundle);
        switchDialogFragment(fragment,mGameNoticeFragment,FLAG_GAME_NOTICE_FRAGMENT);
    }


    private void doNextToAutoLogin(DialogFragment fragment) {
        mAutoLoginDialogFragment = AutoLoginDialogFragment.newInstance();
        switchDialogFragment(fragment, mAutoLoginDialogFragment, FLAG_AUTO_LOGIN_FRAGMENT);
    }

    private void doNextToVersionUpdate(DialogFragment fragment) {
        mVersionUpdateDialogFragment = DownloadDialogFragment.newInstance();
        switchDialogFragment(fragment, mVersionUpdateDialogFragment, FLAG_VERSION_UPDATE_FRAGMENT);
    }


    @Override
    public void doRealNameVerify(String realName, String idCardNumber) {
        //todo
        SimpleAsyncResponseHandler handler = requestCallbackHandler(RealNameResponseParams.class);
        mSumbitVerifyInfoTaskId = HttpEngineApi.getInstance().realName(realName, idCardNumber, handler);
        WL.w(TAG, "login finished.");
    }

    @Override
    public void doBindPhone(String realName, String idCardNumber) {
        //todo
        SimpleAsyncResponseHandler handler = requestCallbackHandler(BindPhoneResponseParams.class);
        mSumbitVerifyInfoTaskId = HttpEngineApi.getInstance().bindPhoneNumber(realName, idCardNumber, handler);
//        finish();
    }

    @Override
    public void doFinishActivity(BaseDialogFragment fragment) {
        if (fragment instanceof AutoLoginDialogFragment) {
            doNextToLogin(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//            if(ThirdLoginUtil.getInstance().isAppInstalled(getApplicationContext())){
//            }else{
//                doNextToLoginMore(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//            }
        }
//        else if (fragment instanceof LoginDialogFragment) {
//            doNextToLogin(mMoreLoginFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//        }
        else if (fragment instanceof CreateXiaohaoFragment) {
            doNextToXiaohaoList(createXiaohaoFragment,fragment.getArguments());
//            doNextToLogin(mMoreLoginFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
        }else if (fragment instanceof AccountListChangeDialogFragment) {

            doNextToChangePassword(accountListChangeDialogFragment,fragment.getArguments());
//            doNextToLogin(mMoreLoginFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
        }else if (fragment instanceof ChangePwdFinalDialogFragment) {

            doNextToAccountChangeList(mChangePasswordFinalFragment,fragment.getArguments());
//            doNextToLogin(mMoreLoginFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
        } else if (fragment instanceof DownloadDialogFragment) {
            Bundle bundle = fragment.getArguments();
            if (bundle.getBoolean("executeLogin")) {
                executeLoginProcess(mVersionUpdateDialogFragment);
            } else {
                finish();
            }
        }

        else if (fragment instanceof LoginDialogFragment||fragment instanceof LoginDialogFragment2) {
            String message = getString(getStringIdentifier("hnssn_sdk_messag_login_cancel"));
            doCallbackLoginResult(Constant.LoginState.LOGIN_CANCEL, message, null);
        }
//        else if (fragment instanceof AccountDialogFragment) {
//            Bundle fragmentArguments = fragment.getArguments();
//            if (fragmentArguments != null) {
//                QuickRegisterResponseParams.QuickRegisterResponseData data = fragmentArguments.getParcelable("quickRegister");
//
//                WL.w(TAG, "login finished.");
//                //跳转到绑定手机号码页面
//                LoginInfo loginInfo = new LoginInfo(data.getId(), data.getTicket(), data.getExpires_in());
//                judgeLoginNextOperationSteps(data.getPopupConfig(),loginInfo,(AccountDialogFragment)fragment);
//
//
////                String message = getString(getStringIdentifier("hnssn_sdk_messag_login_successs"));
////                doCallbackLoginResult(Constant.LoginState.LOGIN_SUCCESS, message, loginInfo);
//                //启动定时器服务，提示用户绑定手机/实名认证
//                TimeTaskService.enqueueWork(this, data.getPopupConfigs());
//
//
//            }
//        }
        else if (fragment instanceof ChangePwdDialogFragment) {
            doNextToLoginMore(mChangePasswordFragment, mCurrentLoginType);
        } else if (fragment instanceof RegisterDialogFragment||fragment instanceof RegisterPhoneDialogFragment) {
            doNextToLoginMore(fragment, mCurrentLoginType);
        } else if (fragment instanceof AccountListDialogFragment) {
            doNextToLoginMore(mAccountListDialogFragment, mCurrentLoginType);
//            doNextToLogin(mAccountListDialogFragment, mCurrentLoginType);
        }else if (fragment instanceof AccountListTokenDialogFragment) {
            doNextToLogin(mAccountListTokenDialogFragment, mCurrentLoginType);
//            if(ThirdLoginUtil.getInstance().isAppInstalled(getApplicationContext())){
//
//            }else{
//                doNextToLoginMore(mAccountListTokenDialogFragment, mCurrentLoginType);
//            }
        }
        else if (fragment instanceof NoticeTipDialogFragment) {
            Bundle bundle = fragment.getArguments();
            LoginInfo loginInfo = bundle.getParcelable("loginInfo");
            String message = getString(getStringIdentifier("hnssn_sdk_messag_login_successs"));
            doCallbackLoginResult(Constant.LoginState.LOGIN_SUCCESS, message, loginInfo);
        }
//        else if (fragment instanceof CertifiesTipDialogFragment) {
//            doNextToRealNameChoose(mCertifiesTipFragment, fragment.getArguments());
//        }
        else if (fragment instanceof CertifiesChooseDialogFragment){
            doNextToRealNameVerify(mCertifiesChooseFragment, fragment.getArguments());
        }else if (fragment instanceof GameNoticeFragment){
//            Bundle bundle = fragment.getArguments();
//            LoginInfo loginInfo = bundle.getParcelable("loginInfo");
//            PopupConfig popupConfig = bundle.getParcelable("popupConfig");
//            popupConfig.setGameNoticeList(null);
//            judgeLoginNextOperationSteps(popupConfig,loginInfo,(GameNoticeFragment)fragment);
        }
        else{
            finish();
        }
    }

    @Override
    public void doChangeUserPassword(String username, String password, String verify) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AccountInfosResponseParams.class, username, password);
        mSumbitUserPasswordInfoTaskId = HttpEngineApi.getInstance().modifyPassword(username, password, verify, handler);
    }



    @Override
    public void doQuickRegister(String username, String password) {
        isRegist = true;
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AuthLoginResponseParams.class, username, password);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().register(username, password, handler);
        setCurrentLoginType(1);
    }
private boolean isRegist=false;
    @Override
    public void doQuickRegister(String username, String password, String code) {
        isRegist = true;
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AuthLoginResponseParams.class, username, password);
        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().register(username, password,code, handler);
        setCurrentLoginType(1);
    }

    @Override
    public void goAccountRegister(BaseDialogFragment fragment) {
        mQuickRegisterFragment = RegisterDialogFragment.newInstance();
        switchDialogFragment(fragment, mQuickRegisterFragment, FLAG_REGISTER_FRAGMENT);
    }


    //    @Override
//    public void doBindOrRealNameVerify(String cellphoneNumber, String verify, String realname, String idCard) {
//        SimpleAsyncResponseHandler handler = requestCallbackHandler(BindPhoneResponseParams.class);
//        mSumbitVerifyInfoTaskId = HttpEngineApi.getInstance().bindPhoneNumber(cellphoneNumber, verify, realname, idCard, handler);
//    }

    @Override
    public void doAlipayAuth() {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(AlipayAuthResponseParams.class);
        mAlipayAuthTaskId = HttpEngineApi.getInstance().alipayAuth(handler);
    }

    public void doAlipayRealname(String code){
        SimpleAsyncResponseHandler handler = requestCallbackHandler(BindPhoneResponseParams.class);
        mAlipayRealnameTaskId = HttpEngineApi.getInstance().alipayRealname(code,handler);
    }

    @Override
    public void onAsyncRequestException(int flag, Exception ex) {
        super.onAsyncRequestException(flag, ex);
        if (mSubmitLoginInfoTaskId == flag) {
            if (mAutoLoginDialogFragment != null && mAutoLoginDialogFragment.isResumed()) {
                doNextToLogin(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//                if(ThirdLoginUtil.getInstance().isAppInstalled(getApplicationContext())){
//                }else{
//                    doNextToLoginMore(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//                }
            }
        }else if (mAlipayRealnameTaskId == flag){
            if (mCertifiesChooseFragment != null && mCertifiesChooseFragment.isResumed()) {
                doNextToRealNameVerify(mCertifiesChooseFragment, mCertifiesChooseFragment.getArguments());
            }
        }
    }

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getCode();
            if (State.SUCCESS == code) {
                if (flag == mSubmitLoginInfoTaskId) {
                    if (response instanceof AuthLoginResponseParams) {
                        String token = ((AuthLoginResponseParams)response).getData().getAccess_token();
                        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
                        wanSDKDataDao.saveCurrentLoginUserTickit(token);
                        wanSDKDataDao.writeLoginAgreePrivate();
                        SimpleAsyncResponseHandler handler = requestCallbackHandler(AccountInfosTokenResponseParams.class);
                        mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().getAccountInfosByToken(handler);
                        String uid = ((AuthLoginResponseParams)response).getData().getId();

                        if(isRegist&& JuHaoWanSDK.getInstance().isToutiaoInit()){
                            isRegist =false;
                            AppLog.setUserUniqueID(uid);
                            GameReportHelper.onEventRegister("default", true);
                        }else if (JuHaoWanSDK.getInstance().isToutiaoInit()){
                            AppLog.setUserUniqueID(uid);
                            GameReportHelper.onEventLogin("default", true);
                        }


                        boolean isAutoLogin = params != null && params.length >= 3 && Boolean.parseBoolean((String) params[2]);

                        String usern = ((AuthLoginResponseParams)response).getData().getUsername();
                        Log.e(TAG,isAutoLogin+".."+uid+".."+usern+".."+(params!=null&&params.length>=2));
                        if (!isAutoLogin) {

                            if(params!=null&&params.length>=2){
                                WL.e("loginresult",uid);
                                AccountInfo accountInfo = new AccountInfo(uid,(String) params[0], (String) params[1]);
                                accountInfo.setEncryptPassword("");
                                wanSDKDataDao.saveUserAccount(accountInfo);
                            }else{
                                AccountInfo accountInfo = new AccountInfo(uid,usern, "");
                                accountInfo.setEncryptPassword("");
                                wanSDKDataDao.saveUserAccount(accountInfo);
                            }
                        }
//                        parseLoginResponseResult((LoginResponseParams) response, params);
                    }else if (response instanceof LoginResponseParams) {
                        parseLoginResponseResult((LoginResponseParams) response, params);
                    }
//                    else if (response instanceof QuickRegisterResponseParams) {
//                        parseOnekeyRegisterResponseResult((QuickRegisterResponseParams) response, params);
//                    }
                    else if (response instanceof AccountInfosResponseParams) {
                        parseAccountInfosResponseResult((AccountInfosResponseParams) response, params);
                    }else if(response instanceof AccountInfosTokenResponseParams){
                        parseAccountInfosTokenResponseResult((AccountInfosTokenResponseParams) response, params);
                    }else if(response instanceof CreatSmallAccountResponseParams){
                        CreatSmallAccountResponseParams data =(CreatSmallAccountResponseParams) response;
                        Bundle bundle = createXiaohaoFragment.getArguments();
                        ArrayList<SimpleUserInfo> temp= bundle.<SimpleUserInfo>getParcelableArrayList("userInfos");
//                        ArrayList<SimpleUserInfo> temp= (ArrayList<SimpleUserInfo>)bundle.getSparseParcelableArray("userInfos");
                        SimpleUserInfo  info = new SimpleUserInfo();
                        info.setId(data.getData().getId());
                        info.setNickname(data.getData().getNickname());
                        info.setUsername(data.getData().getUsername());
                        temp.add(0,info);
                        bundle.putParcelableArrayList("userInfos", temp);

//                        doNextToXiaohaoList(mLoginFragment, bundle);
                        doNextToXiaohaoList(createXiaohaoFragment,bundle);
                    }
                    else {
                        CallbackObservable observable = CallbackObservable.getInstance();
                        String message = "response type is unknown.";
                        observable.callResponseResult(Constant.CallType.CALL_LOGIN, Constant.LoginState.LOGIN_SUCCESS, message, null);
                    }
                } else if (flag == mSumbitUserPasswordInfoTaskId) {
                    if (response instanceof AccountInfosResponseParams) {
                        parseChangeUserPasswordResult((AccountInfosResponseParams) response, params);
                    }else if (response instanceof  ModifyPasswordResponseParams){
                        ModifyPasswordResponseParams date = (ModifyPasswordResponseParams) response;
                        if(date.isSuccess()){
                            String message = getString(getStringIdentifier("hnssn_hint_password_modify_success"));
                            final ConfirmDialog confirmDialog = DialogFactory.createConfirmDialog(UserLoginActivity.this, message);
                            confirmDialog.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    confirmDialog.dismiss();
                                    doNextToLoginMore(mChangePasswordFinalFragment, mCurrentLoginType);

                                }
                            });
                            confirmDialog.show();
                        }
                    }
                } else if (flag == mSumbitRegisterInfoTaskId) {
                    if (response instanceof RegisterResponseParams) {
                        parseQuickRegisterResponseResult((RegisterResponseParams) response, params);
                    }
                } else if (flag == mSumbitVerifyInfoTaskId) {
                    if (response instanceof RealNameResponseParams) {

                        if(loginPop!=null){
                            Intent in = new Intent(UserLoginActivity.this,ActivityActivity.class);
                            in.putExtra("pop",loginPop);
                            startActivity(in);
                        }else{
                            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
                            NoticePopup popup=wanSDKDataDao.getPlatformConfigInfo().getNotice_popup();
                            if(popup!=null){
                                Intent in = new Intent(UserLoginActivity.this,NoticeActivity.class);
                                in.putExtra("pop",popup);
                                startActivity(in);
                            }
                        }

                        String message = getString(getStringIdentifier("hnssn_sdk_messag_login_successs"));
                        doCallbackLoginResult(Constant.LoginState.LOGIN_SUCCESS, message, mRealNameVerifyFragment.getArguments().getParcelable("loginInfo"));
                        finish();
//                        parseRealNameVerifyResponseResult((BindPhoneResponseParams) response, params);
                    }else{
                        finish();
                    }
                }else if (flag == thirdAuthTaskId){
                    if(response instanceof GetUuidResponseParams) {
                        String uuid =((GetUuidResponseParams)response).getData().getUuid();
                        ThirdLoginUtil.getInstance().startLogin(UserLoginActivity.this, uuid,new OnThirdLoginListener() {
                            @Override
                            public void doLoginFinish(int status, String code) {
                                if(status==1){



                                    SimpleAsyncResponseHandler handler = requestCallbackHandler(AuthLoginResponseParams.class);
                                    mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().authCodeLoginToken(code,handler);

//
//                                    SimpleAsyncResponseHandler handler = requestCallbackHandler(LoginResponseParams.class);
//                                    mSubmitLoginInfoTaskId = HttpEngineApi.getInstance().thirdlogin(code, handler);
                                }
                            }
                        });
                    }
                }
                else if (flag == mAlipayRealnameTaskId){
                    if (response instanceof BindPhoneResponseParams) {
                        parseRealNameVerifyResponseResult((BindPhoneResponseParams) response, params);
                    }
                }else if(flag == mAlipayAuthTaskId){
                    if (response instanceof AlipayAuthResponseParams) {
                        final AlipayAuthResponseParams.AlipayAuthResponseData data =((AlipayAuthResponseParams)response).getData();
                        if(!TextUtils.isEmpty(data.getStr())){
                            Runnable authRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    // 构造AuthTask 对象
                                    AuthTask authTask = new AuthTask(UserLoginActivity.this);
                                    // 调用授权接口
                                    // AuthTask#authV2(String info, boolean isShowLoading)，
                                    // 获取授权结果。
                                    final Map<String, String> result = authTask.authV2(data.getStr(), true);
                                    // 将授权结果以 Message 的形式传递给 App 的其它部分处理。
                                    // 对授权结果的处理逻辑可以参考支付宝 SDK Demo 中的实现。
                                   Log.e("MainActivity",result.toString());
                                   String temp = result.toString();
                                   if(!temp.contains("auth_code"))return;
                                   int start = temp.indexOf("auth_code");
                                   temp = temp.substring(start+10);
                                    int end = temp.length();
                                   if(temp.contains("&")){
                                       end = temp.indexOf("&");
                                   }
                                    temp = temp.substring(0,end);
//                                    temp = temp.substring(3,end);
                                    Log.e("MainActivity",temp);
                                    final String finalTemp = temp;
                                    runOnUiThread(new Runnable() {
                                       @Override
                                       public void run() {
                                           doAlipayRealname(finalTemp);
                                       }
                                   });

                                }
                            };
                            Thread authThread = new Thread(authRunnable);
                            authThread.start();


                        }else{
                            doNextToRealNameVerify(mCertifiesChooseFragment, mCertifiesChooseFragment.getArguments());
                        }
                    }
                }
            } else {
//                if(response instanceof AlipayAuthResponseParams){
//                    if(mCertifiesChooseFragment!=null&&mCertifiesChooseFragment.isVisible()){
//                        doNextToRealNameVerify(mCertifiesChooseFragment,mCertifiesChooseFragment.getArguments());
//                    }
////                    parseRealNameVerifyResponseResult(null,null);
//
//                }
//                else
                    if(response instanceof BindPhoneResponseParams){
                    if(mCertifiesChooseFragment!=null&&mCertifiesChooseFragment.isVisible()){
                        doNextToRealNameVerify(mCertifiesChooseFragment,mCertifiesChooseFragment.getArguments());
                    }
//                    parseRealNameVerifyResponseResult(null,null);

                } //自动登录失败，返回帐号登录界面
                else if (response instanceof LoginResponseParams||response instanceof AccountInfosTokenResponseParams) {
                    if (mAutoLoginDialogFragment != null && mAutoLoginDialogFragment.isResumed()) {
                        doNextToLogin(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//                        if(ThirdLoginUtil.getInstance().isAppInstalled(getApplicationContext())){
//
//                        }else{
//                            doNextToLoginMore(mAutoLoginDialogFragment, LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT);
//                        }
                        return;
                    }
                }

                CallbackObservable observable = CallbackObservable.getInstance();
                String message = response.getMsg();
                observable.callResponseResult(Constant.CallType.CALL_LOGIN, code, message, null);
            }
        }

    }
    private Popup loginPop;
    private void parseLoginResponseResult(LoginResponseParams response, Object... params) {
        LoginResponseParams.LoginResponseData data = response.getData();
        loginPop = data.getPopup();
//        loginPop= WanSDK.getInstance().getPlatformConfigInfo().getActivity_popup();
        String uid = data.getTrumpet_user_id();
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        wanSDKDataDao.writeLastLoginType(mCurrentLoginType);
        wanSDKDataDao.saveCurrentLoginUserUID(uid);
        wanSDKDataDao.saveLastLoginSmallAccount(uid);
//        boolean isAutoLogin = params != null && params.length >= 3 && Boolean.parseBoolean((String) params[2]);
//        Log.e("51wan","parseLoginResponseResult"+isAutoLogin);
//        Log.e("51wan","uid"+uid);
////        Log.e("51wan","account"+(String) params[0]);
////        Log.e("51wan","pwd"+(String) params[1]);
////        if (LoginTypeSwitchWatcher.SWITCH_MODE_WHICH_ACCOUNT == mCurrentLoginType && !isAutoLogin) {
//        if (!isAutoLogin) {
//            AccountInfo accountInfo;
//            if(params==null||params.length==0){
//                accountInfo = new AccountInfo(uid, data.getUsername(), "");
//            }else{
//                accountInfo = new AccountInfo(uid, (String) params[0], (String) params[1]);
//
//            }
//            accountInfo.setEncryptPassword("");
//            wanSDKDataDao.saveUserAccount(accountInfo);
//        }

        LoginInfo loginInfo = new LoginInfo(uid, data.getAccess_token(), 7200);

        if(data.getBox_user().getIs_bind_mobile()!=1){
            TimeTaskService.enqueueWork(this);
        }
        if (mAccountListTokenDialogFragment != null && mAccountListTokenDialogFragment.isResumed()) {
            judgeLoginNextOperationSteps(data.getBox_user(), loginInfo, mAccountListTokenDialogFragment);
        }else if (mAccountListDialogFragment != null && mAccountListDialogFragment.isResumed()) {
            judgeLoginNextOperationSteps(data.getBox_user(), loginInfo, mAccountListDialogFragment);
        } else if (mAutoLoginDialogFragment != null && mAutoLoginDialogFragment.isResumed()) {
            judgeLoginNextOperationSteps(data.getBox_user(), loginInfo, mAutoLoginDialogFragment);
        } else {
            judgeLoginNextOperationSteps(data.getBox_user(), loginInfo, mLoginFragment);
        }
    }

//    private boolean isGoToBindCellPhone(PopupConfig popupConfig) {
//        boolean bindPhoen =HttpEngineApi.getInstance().getEngineConduits().readIDcardUiType()==0;
//        if (bindPhoen&&popupConfig != null && popupConfig.isPhonePopup()) {
//            return true;
//        }
////
////        if (popupConfig != null && popupConfig.isIdcardPopup()) {
////            return true;
////        }
//
//        return false;
//    }

    private void judgeLoginNextOperationSteps(UserInfo popupConfig, LoginInfo loginInfo, DialogFragment fragment) {
//        Popup infoPopup = popupConfig != null ? popupConfig.getNoticePopup() : null;
//        ArrayList<GameNoticeModel> noticeModels = popupConfig==null?null:popupConfig.getGameNoticeList();
//        if(noticeModels!=null&&noticeModels.size()>0){
//            Bundle bundle = new Bundle();
//            bundle.putParcelableArrayList("notice",noticeModels);
//            bundle.putParcelable("loginInfo", loginInfo);
//            bundle.putParcelable("popupConfig", popupConfig);
//            doNextToGameNotice(fragment,bundle);
//        }else
            if (popupConfig.getIs_box_real_name()!=1) {

            //跳转到绑定手机号码页面
            Bundle bundle = new Bundle();
            bundle.putParcelable("loginInfo", loginInfo);
                doNextToRealNameVerify(fragment,bundle);
//            bundle.putParcelable("PopupConfig", popupConfig);
//            if (popupConfig.isNoticePopup() && infoPopup != null) {
//                bundle.putParcelable("infoPopup", infoPopup);
//            }

//            doNextToRealNameVerify(fragment, bundle);
//                doNextToCertifiesc
        }
//            else if (popupConfig != null && popupConfig.isNoticePopup() && infoPopup != null) {
//            Bundle bundle = new Bundle();
//            bundle.putParcelable("loginInfo", loginInfo);
//            bundle.putParcelable("infoPopup", infoPopup);
//
//            doNextToNoticeTip(fragment, bundle);
//        }
        else {
//            Popup popup =WanSDK.getInstance().getPlatformConfigInfo().getActivity_popup();
            if(loginPop!=null){
                Intent in =new Intent(UserLoginActivity.this,ActivityActivity.class);
                in.putExtra("pop",loginPop);
               startActivity(in);
            }else{
                HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
                NoticePopup popup=wanSDKDataDao.getPlatformConfigInfo().getNotice_popup();
                if(popup!=null){
                    Intent in = new Intent(UserLoginActivity.this,NoticeActivity.class);
                    in.putExtra("pop",popup);
                    startActivity(in);
                }
            }


            WL.w(TAG, "login finished.");
            String message = getString(getStringIdentifier("hnssn_sdk_messag_login_successs"));
            doCallbackLoginResult(Constant.LoginState.LOGIN_SUCCESS, message, loginInfo);
        }
    }

    private void judgeBindingNextOperationSteps(Fragment fragment, boolean isCanceled) {
//        if (is()) {
//            if (!isCanceled) {
//                //跳转到支付界面
//                Bundle bundle = fragment.getArguments();
//                Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_START_PAY_ACTIVITY);
//                intent.setPackage(getApplicationContext().getPackageName());
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.putExtra("goods", (Goods)bundle.getParcelable("goods"));
//                getApplicationContext().startActivity(intent);
//            }
//            finish();
//        } else if (!isOnlyRealNameVerify()) {
//            Bundle bundle = fragment.getArguments();
//            Popup infoPopup = bundle.getParcelable("infoPopup");
//            if (infoPopup != null) {
//                doNextToNoticeTip(mRealNameVerifyFragment, bundle);
//            } else {
//                LoginInfo loginInfo = bundle.getParcelable("loginInfo");
//                String message = getString(getStringIdentifier("hnssn_sdk_messag_login_successs"));
//                doCallbackLoginResult(Constant.LoginState.LOGIN_SUCCESS, message, loginInfo);
//            }
//        } else {
//            finish();
//        }
    }



    private void parseAccountInfosTokenResponseResult(AccountInfosTokenResponseParams response, Object... params) {
        AccountInfosTokenResponseParams.AccountInfosResponseData data = response.getData();
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        String id = wanSDKDataDao.readDefaultSmallAccount();
        ArrayList<SimpleUserInfo> userInfos = data.getUserInfoList();
        if(TextUtils.isEmpty(id)){
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("userInfos", userInfos);
            bundle.putParcelable("user", data.getBox_user());
            if(mQuickRegisterFragment!=null&&mQuickRegisterFragment.isVisible()){
                doNextToXiaohaoList(mQuickRegisterFragment, bundle);
            }else if(mMoreLoginFragment!=null&&mMoreLoginFragment.isVisible()){
                doNextToXiaohaoList(mMoreLoginFragment, bundle);
            }
            else{
                doNextToXiaohaoList(mLoginFragment, bundle);
            }
        }else{
            boolean hasit = false;
            for (SimpleUserInfo info:userInfos) {
                if(info.getId().equals(id)){
                    hasit = true;
                    break;
                }
            }
            if(hasit){
                doSubmitAuthLoginXiaohaoInfo(id);
            }else{
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("userInfos", userInfos);
                bundle.putParcelable("user", data.getBox_user());
//                doNextToXiaohaoList(mLoginFragment, bundle);
                if(mQuickRegisterFragment!=null&&mQuickRegisterFragment.isVisible()){
                    doNextToXiaohaoList(mQuickRegisterFragment, bundle);
                }else if(mMoreLoginFragment!=null&&mMoreLoginFragment.isVisible()){
                    doNextToXiaohaoList(mMoreLoginFragment, bundle);
                }else{
                    doNextToXiaohaoList(mLoginFragment, bundle);
                }
            }
        }
    }


//    private void parseOnekeyRegisterResponseResult(QuickRegisterResponseParams response, Object... params) {
//        QuickRegisterResponseParams.QuickRegisterResponseData data = response.getData();
//
//        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
//        wanSDKDataDao.saveCurrentLoginUserUID(data.getId());
//        AccountInfo accountInfo = new AccountInfo(data.getId(), data.getName(), data.getPassword());
//        accountInfo.setEncryptPassword(data.getPassword());
//        wanSDKDataDao.saveUserAccount(accountInfo);
//        Bundle bundle = new Bundle();
//        LoginInfo loginInfo = new LoginInfo(data.getId(), data.getTicket(), data.getExpires_in());
//        bundle.putParcelable("loginInfo", loginInfo);
//        bundle.putParcelable("quickRegister", data);
//        doNextToOneKeyLogin(bundle);
//    }

    private void parseQuickRegisterResponseResult(RegisterResponseParams response, Object... params) {
//        RegisterResponseParams.RegisterResponseData data = response.getData();
//
//        String uid = data.getId();
//        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
//        wanSDKDataDao.saveCurrentLoginUserUID(uid);
//
//        AccountInfo accountInfo = new AccountInfo(uid, (String) params[0], (String) params[1]);
//        accountInfo.setEncryptPassword(data.getPassword());
//        wanSDKDataDao.saveUserAccount(accountInfo);
//
//        //跳转到绑定手机号码页面
//        LoginInfo loginInfo = new LoginInfo(uid, data.getTicket(), data.getExpires_in());
//        PopupConfig popupConfig = data.getPopupConfig();
//        judgeLoginNextOperationSteps(popupConfig, loginInfo, mQuickRegisterFragment);
//        if(popupConfig.isIdcardPopup()){
//            //启动定时器服务，提示用户绑定手机/实名认证
//            TimeTaskService.enqueueWork(this, data.getIdcardPopupConfigs());
//        }
    }

    /**
     * change user password result parse
     *
     * @param response
     * @param params
     */
    private void parseChangeUserPasswordResult(AccountInfosResponseParams response, Object...
            params) {
//        if (State.SUCCESS == response.getCode()) {
//            HttpEngineConduits engineConduits = HttpEngineApi.getInstance().getEngineConduits();
//            AccountInfo accountInfo = engineConduits.findUserAccountByUsername((String) params[0]);
//            if (accountInfo != null) {
//                accountInfo.setPassword((String) params[1]);
//            } else {
//                accountInfo = new AccountInfo((String) params[0], (String) params[1]);
//            }
//            engineConduits.saveUserAccount(accountInfo);
//
//            if (mChangePasswordFragment != null && mChangePasswordFragment.isResumed()) {
//                mChangePasswordFragment.doCallbackSubmitReuslt();
//            }
//
//        }
        AccountInfosResponseParams.AccountInfosResponseData data = response.getData();
        ArrayList<SimpleUserInfo> userInfos = data.getUserInfoList();
        if (userInfos!=null&&userInfos.size()>0) {
            Bundle bundle =mChangePasswordFragment.getArguments();
            bundle.putParcelableArrayList("userInfos", userInfos);
            bundle.putString("phone",(String)params[0] );
            bundle.putString("username",(String)params[0] );

            bundle.putString("code", data.getToken());
            doNextToAccountChangeList(mChangePasswordFragment, bundle);

        } else {
            Toast.makeText(UserLoginActivity.this,"当前手机未绑定任何账号",Toast.LENGTH_SHORT).show();
//            doSubmitLoginAccountInfo(userInfos.get(0), data.getToken());
        }
    }

    private void parseAccountInfosResponseResult(AccountInfosResponseParams response, Object... params) {
        AccountInfosResponseParams.AccountInfosResponseData data = response.getData();

        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        wanSDKDataDao.saveLastLoginPhoneNumber((String)params[0]);

        ArrayList<SimpleUserInfo> userInfos = data.getUserInfoList();
        if (userInfos.size() > 1) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("userInfos", userInfos);
            bundle.putString("phone",(String)params[0] );
            bundle.putString("code", data.getToken());
            doNextToAccountList(mMoreLoginFragment, bundle);

        } else {
            doSubmitLoginAccountInfo(userInfos.get(0), data.getToken());
        }
    }

    private void parseRealNameVerifyResponseResult(BindPhoneResponseParams response, Object... params) {
        judgeBindingNextOperationSteps(mRealNameVerifyFragment==null?mCertifiesChooseFragment:mRealNameVerifyFragment, false);
//        if (mRealNameVerifyFragment.isNextRealNameVerify()) {
//            mRealNameVerifyFragment.setCurrentItem(1);
//        } else {
//            judgeBindingNextOperationSteps(mRealNameVerifyFragment, false);
//        }
    }

    private void doCallbackLoginResult(int stateCode, String message, LoginInfo loginInfo) {
        String repsonse = loginInfo == null ? null : loginInfo.toString();
        CallbackObservable observable = CallbackObservable.getInstance();
        observable.callResponseResult(Constant.CallType.CALL_LOGIN, stateCode, message, repsonse);
        finish();
    }
}
